package satir.command;

import java.util.ArrayList;
import java.util.Scanner;

import satir.SatirGame;
import satir.framework.InputValidator;
import satir.player.Player;

/**
 * The Class EnterPlayerFigureCmd.
 * @version 3.0 April 2012
 * @author Creative Family
 */
public class EnterPlayerFigureCmd implements Command {

    /** The satir game. */
    private SatirGame satirGame;

    /**
     * Instantiates a new enter player figure cmd.
     * @param satirGame
     *            the satir game
     */
    public EnterPlayerFigureCmd(final SatirGame satirGame) {
	this.satirGame = satirGame;
    }

    /**
     *  Execute to retrieve user input.
     */
    public void execute() {
	char figure;
	Scanner scanner = new Scanner(System.in);
	ArrayList<Character> selectedFigures = new ArrayList<Character>();
	String input;
	for (int i = 0; i < satirGame.getNumOfPlayer(); i++) {
	    do {
		System.out.println(satirGame.getPlayers(i).getName()
			+ " please choose your figure:");
		input = scanner.next(); // get the player figure from input
	    } while (!isValidFigure(input, selectedFigures));

	    figure = input.charAt(0);
	    setFigure(figure, satirGame.getPlayers(i), selectedFigures);
	}
    }

    /**
     * Sets the figure.
     * @param figure the figure
     * @param player the player
     * @param selectedFigures the selected figures
     */
    private void setFigure(final char figure, final Player player,
	    final ArrayList<Character> selectedFigures) {
	System.out.println("[" + player.getName() + "] your figure is "
		+ figure);
	player.setFigure(figure);
	selectedFigures.add(figure);
    }

    /**
     * Checks if is valid figure.
     * @param input the input
     * @param selectedFigures the selected figures
     * @return true, if is valid figure
     */
    private boolean isValidFigure(final String input,
	    final ArrayList<Character> selectedFigures) {
	boolean isValid = true;
	if (!InputValidator.isCharacter(input)) {
	    System.out.println("Figure Must be one character only!");
	    isValid = false;
	} else if (selectedFigures.contains(input.charAt(0))) {
	    System.out.println("Figure has been choosen!");
	    isValid = false;
	}
	return isValid;
    }
}
